package demo.practice.dp;

public class P931 {
    public static void main(String[] args) {
        P931 p931 = new P931();
        p931.minFallingPathSum(new int[][]{{2, 1, 3}, {6, 5, 4}, {7, 8, 9}});
    }

    public int minFallingPathSum(int[][] matrix) {

        int h = matrix.length;
        int w = matrix[0].length;
        int dp[][] = new int[h][w];
        for (int j = 0; j < w; j++) {
            dp[0][j] = matrix[0][j];
        }


        for (int i = 1; i < h; i++) {
            for (int j = 0; j < w; j++) {
                dp[i][j] = dp[i - 1][j] + matrix[i][j];
                if (j - 1 >= 0) {
                    dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1]+ matrix[i][j]);
                }
                if (j + 1 < w) {
                    dp[i][j] = Math.min(dp[i][j], dp[i - 1][j + 1]+ matrix[i][j]);
                }
            }
        }
        int min = Integer.MAX_VALUE;
        for (int j = 0; j < w; j++) {
            min = Math.min(dp[h - 1][j], min);
        }

        return min;
    }
}
